import React from 'react';
import { connect } from 'react-redux';
import { is } from 'immutable';
import * as css from './style';
import * as action from '../../../redux/action';
import { fetch, fetch_rec, qiniu, isMobile, handleError, dom } from '../../../utils/utils';


class BookPanel extends React.Component {

    componentDidUpdate() {
        // offset 由微信搜索时传递进来，用于直接跳转到某本书的位置
        let offset = this.props.BOOK.getIn(['unrender', 'offset']);

        if (offset) {
            document.querySelectorAll(`.${css.book}`)[offset].scrollIntoView();
            this.props.removeOffset();
        }
    }

    componentDidMount() {
        if (this.props.wxid) {
            fetch_rec(this.props.wxid).done(res => {
                this.props.recBook(res.books.filter(item => item[0]).reduce((a, b) => a.concat(b)));
            })
        }
    }

    shouldComponentUpdate(nextProps) {
        return !is(nextProps.BOOK, this.props.BOOK) || !is(nextProps.UserIsSpread, this.props.UserIsSpread);
    }

    render() {

        let BOOK = this.props.BOOK.get('render');
        let rec_book = this.props.BOOK.get('unrender').toJS().rec_books;
        let Paging = BOOK.get('allpage') ?
            <Part keyword={ BOOK.get('keywords') }
                all={ BOOK.get('allpage') }
                now={ BOOK.get('nowpage') }
                next={ this.props.getBookByNextPage }
                sendMessage={ this.props.sendMessage }
                /> : undefined;

        return (
            <div className={ css.panel } ref="b" data-type="bookwrapper">
                {
                    BOOK.get('books').map((e, i) =>
                        <Book key={i} { ...e.toObject() }
                            showAside={ this.props.showAside }
                            UserIsSpread={this.props.UserIsSpread}
                            spreadUserPanel={this.props.spreadUserPanel}/>
                    )
                }
                <Recommend showAside={ this.props.showAside } recbook={rec_book}/>
                { Paging }
            </div>
        )
    }
}

/*
class LibraryInfo extends Component{
    render(){
        return (
            <div className={ css.libinfo }>
                <h3>读者信息</h3>
                <div>
                    <table border="1">
                        <thead>
                            <tr>
                                <th>库室名称</th>
                                <th>开放时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr data-combind="true">
                                <td>通信计算机书库</td>
                                <td rowSpan="5">
                                    <span>
                                        周一至周五：08:00～12:00　13:30～21:30<br/>
                                        周六至周日：14:00～21:30
                                    </span>
                                </td>
                            </tr>
                            <tr data-combind="true">
                                <td>数理书库</td>
                            </tr>
                            <tr data-combind="true">
                                <td>文艺书库</td>
                            </tr>
                            <tr data-combind="true">
                                <td>社科书库</td>
                            </tr>
                            <tr>
                                <td>外文书库</td>
                            </tr>

                            <tr>
                                <td>现刊阅览室</td>
                                <td>
                                    <span>
                                        周一至周五：08:00～12:00　13:30～21:30<br/>
                                        周六至周日：09:00～12:00　13:30～21:30
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td>过刊阅览室</td>
                                <td>
                                    <span>
                                        周一至周五：08:00～12:00　14:30～18:00
                                    </span>
                                </td>
                            </tr>
                            <tr data-combind="true">
                                <td>教师阅览室</td>
                                <td rowSpan="2">
                                    <span>
                                        周一至周五：08:00～12:00　14:30～21:30<br/>
                                        周六至周日：14:00～21:30
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td>国防阅览室</td>
                            </tr>
                            <tr>
                                <td>电子阅览室</td>

                                <td>
                                    <span>
                                        周一至周五：08:00～21:30<br/>
                                        周六至周日：14:00～21:30
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <td>还书处</td>
                                <td>
                                    <span>
                                        周一至周五：08:00～18:00<br/>
                                        周六至周日：14:00～17:30
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        )
    }
}
*/

/**
 *  books
 *  @props object , state.render.books[i]
 *  @props showAside, redux acton
 *  @props UserIsSpread, redux acton
 *  @props spreadUserPanel, redux acton
 */
class Book extends React.Component {
    render() {
        let { isbn, showAside, ...detail } = this.props;
        return (
            <div className={ css.book }>
                <Image isbn={ isbn } />
                <Detail { ...detail } />
                <More info={ this.props }
                    showAside={ showAside }
                    UserIsSpread={ this.props.UserIsSpread }
                    spreadUserPanel={this.props.spreadUserPanel}/>
            </div>
        )
    }
}


/**
 *  book image
 *  @props isbn: string
 */
class Image extends React.Component {
    render() {
        let isbn = this.props.isbn;
        return (
            <div className={ css.image }>
                <img src={ `${qiniu}/${isbn}` }/>
            </div>
        )
    }
}


/**
 *  book detail
 *  @props ... , detail data
 */
class Detail extends React.Component {
    render() {
        let detail = this.props;
        return (
            <div className={ css.bookbase }>
                <p title={ detail.title }>{ detail.title }</p>
                <small>{ detail.author}</small>
                <small>{ detail.year }</small>
                <small>{ detail.press }</small>
            </div>
        )
    }
}


/**
 *  get more info
 *  @props info: parent props
 *  @props showAside: redux action
 *  @props UserIsSpread: bool
 *  @props spreadUserPanel: redux action
 */
class More extends React.Component {

    constructor(props) {
        super(props);
        this.getMore = this.getMore.bind(this);
        this.move = this.move.bind(this);
        this.end = this.end.bind(this);
    }

    getMore() {
        if (!(isMobile && this.props.UserIsSpread)) {
            this.props.showAside(this.props.info);
        }
    }

    move() {
        this.havemove = true;
    }

    end(e) {
        if (this.havemove === true) {
            e.preventDefault();
        } else {
            if (isMobile && this.props.UserIsSpread) {
                this.props.spreadUserPanel();
                e.preventDefault();
                return false;
            } else {
                this.props.showAside(this.props.info);
            }
        }
        this.havemove = false;
    }
    render() {
        return (
            <div className={ css.more }>
                <button onClick={ this.getMore }
                    onTouchEnd={ this.end }
                    onTouchMove={ this.move }
                    data-type="morebtn">详细信息</button>
            </div>
        )
    }
}


/**
 *  page paging.
 *  @props keyword: string
 *  @props all: int
 *  @props now: int
 *  @props next: int
 *  @props sendMessage: redux action
 */
class Part extends React.Component {

    updatePage(e) {
        e.preventDefault();
        fetch({
            do: 'search',
            keyword: this.props.keyword,
            page: e.target.getAttribute('data-target')
        }).done(res => {
            dom('div[data-type="bookwrapper"] > div:first-child').scrollIntoViewIfNeeded();
            this.props.next(res);
        }).fail(handleError.bind(this));
    }

    render() {
        let all = this.props.all;
        let now = this.props.now;
        let start = Math.max(1, now - 4);
        let end = Math.min(all, now + 5 + (now <= 4 ? Math.min(10, all) - (now + 5) : 0));
        let list = [];

        for (let i = start; i <= end; i++) {
            list.push(i);
        }

        return (
            <div className={ css.part }
                data-pdbefore={ `${now === 1 ? true : false}` }
                data-pdafter={ `${now === all ? true : false}` }>
                {
                    now === 1 ? undefined :
                        <span onClick={this.updatePage.bind(this) }
                            onTouchStart={this.updatePage.bind(this) }
                            className={ css.partNum }
                            data-step="before"
                            data-target={now - 1}>上一页</span>
                }
                {
                    list.map(function(e, i) {
                        return <span onClick={this.updatePage.bind(this) }
                            onTouchStart={this.updatePage.bind(this) }
                            className={ css.partNum }
                            data-target={e}
                            data-cur={e === now}
                            key={i}>{e}</span>
                    }.bind(this))
                }
                {
                    now === all ? undefined :
                        <span onClick={this.updatePage.bind(this) }
                            onTouchStart={this.updatePage.bind(this) }
                            className={ css.partNum }
                            data-step="after"
                            data-target={now + 1}>下一页</span>
                }
            </div>
        )
    }
}


class Recommend extends React.Component {

    constructor(props) {
        super(props);
        this.onClick = this.onClick.bind(this);
    }

    onClick(e) {
        if (e.target.nodeName === 'SPAN' || e.target.nodeName === 'IMG') {
            let ele = e.target.parentElement;
            this.props.showAside({
                'title': ele.getAttribute('data-title'),
                'isbn': ele.getAttribute('data-isbn'),
                'searchId': ele.getAttribute('data-searchId'),
                'allNum': ele.getAttribute('data-allNum'),
                'on': ele.getAttribute('data-on')
            });
        }
    }

    render() {
        if (this.props.recbook.length === 0) return null;

        return (
            <div className={css.recbox}>
                <h3 className={css.rectitle}>根据您以往的搜索结果进行推荐</h3>
                <ul>
                    {
                        this.props.recbook.map((item, i) =>
                            <li className={css.recbook} onClick={this.onClick}
                                data-title={item.title} data-isbn={item.isbn.replace(/-/g, '') }
                                data-searchId={item.searchId} data-allNum={item.allNum}
                                data-on={item.on} key={i}>
                                <img src={`${qiniu}/${item.isbn.replace(/-/g, '')}`} />
                                <span>{item.title}</span>
                            </li>)
                    }
                </ul>
            </div>
        )
    }
}

export default connect(state => ({
    BOOK: state.BOOK,
    wxid: state.USER.getIn['unrender', 'WXId'],
    UserIsSpread: state.USER.getIn(['unrender', 'isSpread'])
}), action)(BookPanel);
